<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ExportController
{
    public function exportCsv(Request $request)
    {
        $request->validate([
            'name'=>'required|string',
            'content'=>'required|string',
        ]);
        $name=$request->post('name');
        $content=$request->post('content');
        $content = str_replace("'", '"', $content);
        $content=json_decode($content,true);
        if (!str_ends_with(strtolower($name),'.csv')){
            $name .= '.csv';
        }
        if (!is_array($content) || !is_array($content[0]??null)){
            return response()->json(['message'=>'内容格式错误'],200);
        }
        if (!count($content)){
            return response()->json(['message'=>'内容不能为空'],200);
        }
        $title=array_keys($content[0]);
        $output=fopen('php://temp','r+');
        fputs($output,"\xEF\xBB\xBF");
        fputcsv($output,$title);
        foreach($content as $row){
            $values=array_map(function($column)use($row){
                return $row[$column]??'';
            },$title);
            fputcsv($output,$values);
        }
        rewind($output);
        $csvContent=stream_get_contents($output);
        fclose($output);
        $path='exports/csv/'.date('Y-m-d').'/'.$name;
        Storage::disk('public')->put($path,$csvContent);
        $url=Storage::disk('public')->url($path);
        return response()->json(['data'=>$url,'message'=>'导出成功'],200);

    }
    public function exportCsv2(Request $request)
    {
        // 验证请求参数
        $request->validate([
            'name' => 'required|string',
            'content' => 'required|array',
            'content.*' => 'array'
        ]);

        $content = $request->input('content');
        $fileName = $request->input('name');

        // 确保文件名以.csv结尾
        if (!str_ends_with(strtolower($fileName), '.csv')) {
            $fileName .= '.csv';
        }

        // 如果内容为空，返回错误
        if (empty($content)) {
            return response()->json(['error' => '内容不能为空'], 400);
        }

        // 获取表头（对象的所有键）
        $headers = array_keys($content[0]);

        // 创建CSV内容
        $output = fopen('php://temp', 'r+');

        // 写入UTF-8 BOM，解决Excel打开中文乱码问题
        fputs($output, "\xEF\xBB\xBF");

        // 写入表头
        fputcsv($output, $headers);

        // 写入数据行
        foreach ($content as $row) {
            // 确保按照表头顺序获取值
            $values = array_map(function ($header) use ($row) {
                return $row[$header] ?? '';
            }, $headers);
            
            fputcsv($output, $values);
        }

        // 获取生成的内容
        rewind($output);
        $csvContent = stream_get_contents($output);
        fclose($output);

        // 存储文件
        $path = 'exports/' . date('Y-m-d') . '/' . $fileName;
        Storage::disk('public')->put($path, $csvContent);

        // 生成下载链接
        $url = Storage::disk('public')->url($path);

        return response()->json([
            'success' => true,
            'url' => $url
        ]);
    }
}